package http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 执行Http请求
 * 
 * @author Administrator
 *
 */
public class HttpClientUtils {

	/**
	 * 
	 * postReqeust ：Post请求方法
	 *
	 * @param url 请求地址
	 * @param params 请求参数，Map<String,String>,key为参数名，value为参数内容
	 * @return
	 * @throws Exception <对方法参数的简单描述>
	 * @return <方法的返回值> <对返回值的简单描述>
	 * @throws <抛出的异常><抛出的异常的描述>
	 * 
	 * @see <参见的内容>
	 */
	public static String postReqeust(String url, Map<String, String> params) throws Exception{
		
		StringBuilder responseContent = new StringBuilder();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		for(String key : params.keySet()){
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		
		try {
			//System.out.println(response2.getStatusLine());
			HttpEntity entity2 = response2.getEntity();
			// do something useful with the response body
			// and ensure it is fully consumed
			InputStream is = entity2.getContent();
			byte[] bytes = new byte[1024];
			int len;
			while((len = is.read(bytes)) > 0){
				responseContent.append(new String(bytes, 0, len));
			}
			
			EntityUtils.consume(entity2);
		} finally {
			response2.close();
		}
		
		return responseContent.toString();
	}
	
	
	public static void main(String[] args) {
		/*try {
			URL url = new URL("http://192.168.60.66/users/sign_in");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10000);
			//conn.setRequestProperty("reqeust", "1111111111");
			System.out.println(conn.getResponseCode());
			System.out.println(conn.getResponseMessage());
			InputStream is = conn.getInputStream();
			StringBuilder sb = new StringBuilder();
			byte[] read = new byte[1024];
			while((is.read(read))!=-1){
				sb.append(new String(read));
			}
			System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}

}
